#coding:utf-8
import pycurl
from io import BytesIO
import demjson
def PCurl(url, headers, AllowRedirects, timeout,charset):
    try:
        header = []
        for key in headers.keys():
            head = key + ': ' + headers[key]
            header.append(head)
        if AllowRedirects == True:
            AllowRedirects = 1
        else:
            AllowRedirects = 0
        bytes = BytesIO()
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.CONNECTTIMEOUT, timeout)  # 连接超时
        c.setopt(pycurl.WRITEFUNCTION, bytes.write)  # 写进字节串
        c.setopt(pycurl.TIMEOUT, timeout)  # 读取超时
        c.setopt(pycurl.FOLLOWLOCATION, AllowRedirects)  # 重定向
        c.setopt(pycurl.MAXREDIRS, 2)  # 最大重定向次数
        c.setopt(pycurl.SSL_VERIFYPEER, 0)  # SSL验证1
        c.setopt(pycurl.SSL_VERIFYHOST, 0)  # SSL验证2
        c.setopt(pycurl.HEADER, True)  # 扩展headrs
        c.setopt(pycurl.HTTPHEADER, header)
        c.setopt(pycurl.USERAGENT,
                 "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.168 Safari/537.36")
        c.perform()
        content = bytes.getvalue()
        # 智能解码耗时太长,改为人工选择编码
        result = content.decode(charset, 'ignore')
        del header
        del content
        # del charset
        return result
    except Exception  as e:
        print('PCurl:', e)
        return False

res  = PCurl('http://www.utmtoken.com/js/czjl.js',{'Host': 'www.utmtoken.com'},False,10,'utf-8')
print(res)
exit()
data = {
    'charset': 'utf-8',
    'AllowRedirects': 'False',
    'ContainList': ['CenterVoucherHandler'],
    'ExcludeList': ['cloudflare','cfduid'],
    'Headers': "{'Host': 'www.utmtoken.com','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36 QQBrowser/4.3.4986.400','Connection':'close'}",
    'Path': '/js/czjl.js',
    'SSL': 'False',
    'ScanType': 'GET',
    'Thread': 300,
    'TimeOut': 1,
}
CONFIG = '''{     'charset': 'gb2312',     'AllowRedirects': 'False',     'ContainList': ['13,1105,279,1167'],     'ExcludeList': ['waf'],     'Headers': "{'Host': 'www.suzhoucec.com','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36 QQBrowser/4.3.4986.400','Connection':'close'}",     'Path': '/ex/201802/ezhoukan201802.html',     'SSL': 'False',     'ScanType': 'GET',     'Thread': 300,     'TimeOut': 1, }'''
CONFIG = demjson.decode(CONFIG)
CONFIG['TASKID'] = '1'

print(demjson.encode(CONFIG))